package nachos.threads;
import nachos.machine.*;
import java.io.*;

class CommandLine implements Runnable
{
	public CommandLine() 
	{
		in = new InputStreamReader(System.in); 
		next_command = ""; 
		option = "";
		input = 0;
		number = 0;
	}

	public void run()
	{
		while(true)
		{
			System.out.print("nachos < ");
			try{input = in.read();} catch (IOException ex){}
		//Get the input as next_command
			while(input != 13)
			{
				if(((char)(input)) == ' ' && next_command.equals("Prime"))
				{
					System.out.print(" ");
					try{input = in.read();} catch (IOException ex) {}
					while(input != 13)
					{
						if(((char)(input)) == ' ')
						{
							System.out.print(" ");
							number = Integer.parseInt(option);
							option = "";
							try{input = in.read();} catch (IOException ex) {}
							while(input != 13)
							{
								option = option + (char)(input);
								System.out.print((char)(input));
								try{input = in.read();} catch (IOException ex) {}
							}
						}
						else
						{
							option = option + (char)(input);
							System.out.print((char)(input));
							try{input = in.read();} catch (IOException ex) {}
						}
					}
				}
				else
				{
					next_command = next_command + (char)(input);
					System.out.print((char)(input));
					try{input = in.read();} catch (IOException ex){}
				}
			}
			System.out.println();
			
			
		//next_command = the input ... number and option initialized
			if(next_command.equals("KThread"))
				KThreadTest.runTest();
			else if(next_command.equals("Communicator"))
				CommunicatorTest.runTest();
			else if(next_command.equals("Prime") && option.equals("-r"))
			{
				KThread prime = new KThread(new PrimePool(0,number+1,1));
				prime.fork();
				prime.join();
			}
			else if(next_command.equals("Prime") && option != "")
			{
				number = Integer.parseInt(option);
				(new KThread(new PrimePool(number,number+1,1))).fork();

			}
			else if(next_command.equals("help") || next_command.equals("h"))
			{
				System.out.println("  Possible commands:");
				System.out.println("     KThread             - runs the test for KThread.join()");
				System.out.println("     Communicator        - runs the test for the Communicator");
				System.out.println("     Prime [number] [-r] - determines if a number is prime");
				System.out.println("                         - if -r is included, will compute results recursively");
			}
			else if(next_command.equals("exit"))
				break;
			KThread.currentThread().yield();
			KThread.currentThread().yield();
		
		//reset next_command;
			next_command = "";
			option = "";
			number = 0;
		}
	}
	
	private int input;
	private int number;
	private String option;
	private Reader in;
	private String next_command;
}
